package com.resou.reader.bookdetail.comment.detail;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.R;
import com.resou.reader.api.entry.BaseComment;
import com.resou.reader.api.entry.CommentBean;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookdetail.adapter.CommmentDetailAdapter;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.view.PopupWindowView;
import com.resou.reader.utils.CircularAnimUtil;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.PopWindowUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.SoftInputUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.CircleImageView;
import com.resou.reader.view.StarRatingBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 评论详情
 */
public class CommentDetailActivity extends ResouBaseActivity<CommentDetailPresenter> implements ICommentDetailContract.ICommentDetailView,
        BaseQuickAdapter.OnItemChildClickListener, View.OnClickListener, TextWatcher
        , OnRefreshLoadMoreListener {

    public static void start(Context context, String bookId, String commentId) {
        Intent starter = new Intent(context, CommentDetailActivity.class);
        starter.putExtra("bookId", bookId);
        starter.putExtra("commentId", commentId);
        context.startActivity(starter);
    }

    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.ivMore)
    ImageView ivMore;
    @BindView(R.id.llHeader)
    RelativeLayout llHeader;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.etCommentDes)
    EditText etCommentDes;
    @BindView(R.id.tvSend)
    TextView tvSend;
    @BindView(R.id.rlBottom)
    RelativeLayout rlBottom;

    /**
     * 头部控件
     */
    View view;

    CircleImageView cvUserPic;  //头像
    TextView tvUserName; //昵称
    StarRatingBar starRatingBar; //星级
    TextView tvCommentDes;// 描述
    TextView tvTime; //时间
    LinearLayout llPraise; //点赞
    TextView tvLikeNum; //点赞数量
    ImageView ivLookMore; //查看
    ImageView ivlike; //喜欢图标
    LinearLayout llemptyPage;//无评论页面容器
    TextView tvInfo;//空页面文案
    TextView tvAllComment;// 全部回复；

    CommmentDetailAdapter commmentDetailAdapter;

    PopWindowUtils popMenu;
    PopWindowUtils popMenuChild;

    RelativeLayout rlReport;
    RelativeLayout rlDelete;
    RelativeLayout rlReportChild;
    RelativeLayout rlDeleteChild;
    BottomSheetDialog dialog = null;
    String bookId;
    String commentId;
    int page = 0;
    CommentBean.ReviewlistBean bean;
    String beType = "5";
    int pos = 0;
    AlertDialog alertDialog;
    int report = 0;

    @Override
    protected void initStatusBar() {

    }

    @Override
    protected void initPresenter() {
        mPresenter = new CommentDetailPresenter(this);
    }

    @Override
    protected void initView() {
        bookId = getIntent().getStringExtra("bookId");
        commentId = getIntent().getStringExtra("commentId");
        getHeaderView();
        commmentDetailAdapter = new CommmentDetailAdapter(R.layout.commend_detail_item, null);
        commmentDetailAdapter.addHeaderView(view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(commmentDetailAdapter);
        commmentDetailAdapter.setOnItemChildClickListener(this);
        mSmartRefreshLayout.setOnRefreshLoadMoreListener(this);
        etCommentDes.addTextChangedListener(this);
        initPopView();
        initDialog();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_comment_detail;
    }

    @Override
    public void retryRefreshData() {
        mPresenter.quearCommentDetail(commentId, page);
    }

    @Override
    public void initData() {
        mPresenter.quearCommentDetail(commentId, page);
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
    }

    @Override
    public void showError(Throwable throwable) {
        dissLoading();
        ToastUtil.makeShortToast("网络异常");
        showNetErrorView(R.id.rlContents);
    }

    @Override
    public void showEmpty() {

    }


    @Override
    public void showCommentDetail(CommentBean commentBean) {
        setDataHeader(commentBean);
    }

    @Override
    public String getTextDes() {
        return etCommentDes.getText().toString().trim().replaceAll(" ", "");
    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return mSmartRefreshLayout;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void sendCommentSuccess() {
        EventBus.getDefault().post(new CommentBean());
        page = 0;
        mPresenter.quearCommentDetail(commentId, page);
        /**
         * 将输入内容制空
         */
        etCommentDes.setText("");
        SoftInputUtils.hideSoftInputKeyBoard(this, etCommentDes);
    }

    @Override
    public void sendCommentFail() {
        alertDialog.show();
    }

    @Override
    public void likePariseSuccess() {
        EventBus.getDefault().post(new CommentBean());
        page = 0;
        mPresenter.quearCommentDetail(commentId, page);
    }

    @Override
    public void reportSuccess() {
        ToastUtil.makeText(this, "举报成功", 2000).show();
        page = 0;
        mPresenter.quearCommentDetail(commentId, page);
    }

    /**
     * 删除成功
     *
     * @param state 0表示书评 删除 ，1书评子回复删除
     */
    @Override
    public void deleteCommentSuccess(int state) {
        ToastUtil.makeText(this, "删除成功", 2000);
        EventBus.getDefault().post(new MessageEvent("intent_comment"));
        EventBus.getDefault().post(new CommentBean());
        if (state == 0) {
            finish();
        } else {
            page = 0;
            mPresenter.quearCommentDetail(commentId, page);
        }
    }


    @OnClick({R.id.ivBack, R.id.ivMore, R.id.tvSend})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivMore:
                popMenu.showAsDropDown(ivMore, 0, 0, 0);
                break;
            case R.id.tvSend:
                if (isNetwork()) {
                    if (getTextDes().length() == 0) {
                        ToastUtil.makeShortToast("请输入回复内容");
                        return;
                    }
                    mPresenter.sendComment(getTextDes(), bookId, commentId, (int) starRatingBar.getStarMark());
                }

                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             *书评点赞
             */
            case R.id.llPraise:
                if (isNetwork()) {
                    if (PreferenceUtil.getInstance(this).getlocalCommentPariseState(commentId)) {
                        CircularAnimUtil.propertyValuesHolderDown(v);
                    } else {
                        mPresenter.remoteLikeParise(Integer.valueOf(commentId));
                    }
                }

                break;
            /**
             * 书评举报
             */
            case R.id.rlReport:
                if (isNetwork()) {
                    if (popMenu != null) {
                        popMenu.dissmiss();
                    }
                    report = 1;
                    dialog.show();
                }
                break;
            /**
             * 书评删除
             */
            case R.id.rlDelete:
                if (isNetwork()) {
                    if (popMenu != null) {
                        popMenu.dissmiss();
                    }
                    mPresenter.deleteComment(0, commentId);
                }

                break;
            case R.id.rlDeleteChild:
                if (isNetwork()) {
                    if (popMenuChild != null) {
                        popMenuChild.dissmiss();
                    }
                    mPresenter.deleteComment(1, bean.getId() + "");
                }
                break;
            /**
             * 评论回复举报
             */
            case R.id.rlReportChild:
                if (isNetwork()) {
                    if (popMenuChild != null) {
                        popMenuChild.dissmiss();
                    }
                    report = 0;
                    dialog.show();
                }
                break;
            case R.id.tvReport1:
                if (isNetwork()) {
                    if (dialog != null) {
                        dialog.cancel();
                    }
                    if (report == 0) {
                        mPresenter.reportComment(1, bean.getId() + "", beType);
                    } else {
                        mPresenter.reportComment(4, commentId, "4");
                    }
                }
                break;
            case R.id.tvReport2:
                if (isNetwork()) {
                    if (dialog != null) {
                        dialog.cancel();
                    }
                    if (report == 0) {
                        mPresenter.reportComment(2, bean.getId() + "", beType);
                    } else {
                        mPresenter.reportComment(4, commentId, "4");
                    }
                }

                break;
            case R.id.tvReport3:
                if (isNetwork()) {
                    if (dialog != null) {
                        dialog.cancel();
                    }
                    if (report == 0) {
                        mPresenter.reportComment(3, bean.getId() + "", beType);
                    } else {
                        mPresenter.reportComment(4, commentId, "4");
                    }
                }
                break;
            case R.id.tvReport4:
                if (isNetwork()) {
                    if (dialog != null) {
                        dialog.cancel();
                    }
                    if (report == 0) {
                        mPresenter.reportComment(4, bean.getId() + "", beType);
                    } else {
                        mPresenter.reportComment(4, commentId, "4");
                    }
                }

                break;
            case R.id.tvReport5:
                if (isNetwork()) {
                    if (dialog != null) {
                        dialog.cancel();
                    }
                    if (report == 0) {
                        mPresenter.reportComment(5, bean.getId() + "", beType);
                    } else {
                        mPresenter.reportComment(4, commentId, "4");
                    }
                }
                break;

            case R.id.tvCancell:
                if (dialog != null) {
                    dialog.cancel();
                }
                break;
        }
    }

    /**
     * 获取头部实例
     */
    private void getHeaderView() {
        if (view == null) {
            view = LayoutInflater.from(this).inflate(R.layout.comment_detail_header, null);
        }
        cvUserPic = view.findViewById(R.id.cvUserPic);
        tvUserName = view.findViewById(R.id.tvUserName);
        starRatingBar = view.findViewById(R.id.starRatingBar);
        tvCommentDes = view.findViewById(R.id.tvCommentDes);
        tvTime = view.findViewById(R.id.tvTime);
        llPraise = view.findViewById(R.id.llPraise);
        tvLikeNum = view.findViewById(R.id.tvLikeNum);
        ivLookMore = view.findViewById(R.id.ivLookMore);
        ivlike = view.findViewById(R.id.ivLike);
        llemptyPage = view.findViewById(R.id.llemptyPage);
        tvInfo = view.findViewById(R.id.tvInfo);
        llemptyPage.setVisibility(View.GONE);
        tvAllComment = view.findViewById(R.id.tvAllComment);
        llPraise.setOnClickListener(this);
    }


    /***
     *设置头部评论显示数据
     * @param commentBean
     */
    private void setDataHeader(CommentBean commentBean) {
        RequestOptions options = new RequestOptions();
        options.format(DecodeFormat.PREFER_RGB_565);
        Glide.with(this).load(commentBean.getHead_pic() + "").apply(options).into(cvUserPic);
        tvUserName.setText(commentBean.getNickName() + "");
        starRatingBar.setMaxStarMark(5);
        starRatingBar.setIsClickable(false);
        starRatingBar.setStarMark(Float.valueOf(commentBean.getLevel()));
        tvCommentDes.setText(commentBean.getContent() + "");
        tvTime.setText("发布于  " + DateUtils.getTheDayFromNow(commentBean.getCreate_date()));
        if (tvTime.getText().toString().equals("刚刚")) {
            tvTime.setTextColor(getResources().getColor(R.color.theme_color));
        } else {
            tvTime.setTextColor(getResources().getColor(R.color.color757575));
        }
        tvLikeNum.setText(commentBean.getPraisenum() == 0 ? "点赞" : commentBean.getPraisenum() + "");
        tvAllComment.setText("全部回复 (" + commentBean.getReviewCount() + ")");
        if (PreferenceUtil.getInstance(this).getlocalCommentPariseState(commentId)) {
            ivlike.setImageResource(R.mipmap.ic_commentliked);
        } else {
            ivlike.setImageResource(R.mipmap.ic_commentlike);
        }
        if (commentBean.getReviewlist() == null || commentBean.getReviewlist().size() == 0) {
            llemptyPage.setVisibility(View.VISIBLE);
            tvInfo.setText("抢个沙发~");
            commmentDetailAdapter.getData().clear();
            commmentDetailAdapter.notifyDataSetChanged();
        } else {

            llemptyPage.setVisibility(View.GONE);
        }
        if (page == 0) {
            commmentDetailAdapter.setNewData(commentBean.getReviewlist());
        } else {
            commmentDetailAdapter.addData(commentBean.getReviewlist());
        }
        if (UserInstance.getUserId().equals(commentBean.getUid() + "")) {
            isOwnComment(true);
        } else {
            isOwnComment(false);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        bean = (CommentBean.ReviewlistBean) adapter.getData().get(position);
        pos = position;
        switch (view.getId()) {
            case R.id.llPraise:
                if (PreferenceUtil.getInstance(this).getlocalCommentPariseState(bean.getId() + "")) {
                    CircularAnimUtil.propertyValuesHolderDown(view);
                } else {
                    mPresenter.remoteLikeParise(bean.getId());
                }
                break;
            case R.id.ivLookMore:
                if (UserInstance.getUserId().equals(bean.getUid() + "")) {
                    isOwnCommentChild(true);
                } else {
                    isOwnCommentChild(false);
                }
                popMenuChild.showAsDropDown(view, 0, 0, 0);
                break;
        }
    }

    /**
     * 初始化pop视图
     */
    private void initPopView() {
        /**
         * 根评论pop
         */
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_commentmenu, null);
        //处理popWindow 显示内容
        rlReport = contentView.findViewById(R.id.rlReport);
        rlDelete = contentView.findViewById(R.id.rlDelete);
        rlReport.setOnClickListener(this);
        rlDelete.setOnClickListener(this);
        popMenu = new PopWindowUtils.PopupWindowBuilder(this).setView(contentView).create();


        /**
         * 子回复的pop
         */
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_commentmenu2, null);
        rlReportChild = view.findViewById(R.id.rlReportChild);
        rlDeleteChild = view.findViewById(R.id.rlDeleteChild);
        rlReportChild.setOnClickListener(this);
        rlDeleteChild.setOnClickListener(this);
        popMenuChild = new PopWindowUtils.PopupWindowBuilder(CommentDetailActivity.this).setView(view).create();

        /**
         * 举报Pop
         */
        View reportView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_reportview, null);
        reportView.findViewById(R.id.tvReport1).setOnClickListener(this);
        reportView.findViewById(R.id.tvReport2).setOnClickListener(this);
        reportView.findViewById(R.id.tvReport3).setOnClickListener(this);
        reportView.findViewById(R.id.tvReport4).setOnClickListener(this);
        reportView.findViewById(R.id.tvReport5).setOnClickListener(this);
        reportView.findViewById(R.id.tvCancell).setOnClickListener(this);
        reportView.findViewById(R.id.design_bottom_sheet).setBackground(new BitmapDrawable());
        dialog = new BottomSheetDialog(this);
        dialog.setContentView(reportView);
        dialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackground(new BitmapDrawable());

    }


    /**
     * 判断是否是自己的回复
     *
     * @param isOwn
     */
    private void isOwnComment(boolean isOwn) {
        if (isOwn) {
            rlReport.setVisibility(View.GONE);
            rlDelete.setVisibility(View.VISIBLE);
        } else {
            rlReport.setVisibility(View.VISIBLE);
            rlDelete.setVisibility(View.GONE);
        }
    }

    /**
     * 子回复
     *
     * @param isOwn
     */
    private void isOwnCommentChild(boolean isOwn) {
        if (isOwn) {
            rlReportChild.setVisibility(View.GONE);
            rlDeleteChild.setVisibility(View.VISIBLE);
        } else {
            rlReportChild.setVisibility(View.VISIBLE);
            rlDeleteChild.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (popMenuChild != null) {
            popMenuChild.dissmiss();
        }
        if (dialog != null) {
            dialog.cancel();
        }
        if (popMenu != null) {
            popMenu.dissmiss();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        mPresenter.quearCommentDetail(commentId, page);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 0;
        mPresenter.quearCommentDetail(commentId, page);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > 0) {
            tvSend.setClickable(true);
            tvSend.setTextColor(getResources().getColor(R.color.white));
        } else {
            tvSend.setClickable(false);
            tvSend.setTextColor(getResources().getColor(R.color.colorfff77567));
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void initDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_violationinfo, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        alertDialog = builder.create();
        view.findViewById(R.id.tvKnow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
            }
        });
    }
}


